package com.chilly.netty.websocket.action.reconnTimeoutHeart;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Created by Chilly Cui on 2020/12/25.
 */
public class HandlerServerReconnTimeoutHeart extends ChannelInboundHandlerAdapter {

    //通道数组，保存所有注册到 EventLoop的通道
    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //处理收到的消息，并反馈消息到客户端
        ByteBuf in = (ByteBuf) msg;
        System.out.println("收到客户端发过来的消息：" + in.toString(CharsetUtil.UTF_8));

        //写入并发送消息到客户端
        String strDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss SSS"));
        ctx.writeAndFlush(Unpooled.copiedBuffer("这是服务器端在 Read方法中发送的消息" + strDateTime + "\r\n", CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    //新建连接时触发
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        System.out.println("客户端：" + incoming + "已连接");
        channels.add(incoming);
    }

    //断开连接时触发
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        System.out.println("客户端：" + incoming + "已断开");
        channels.remove(incoming);
    }

    //通道处于活动状态触发的动作，该方法只会在通道建立时调用一次
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        System.out.println("客户端：" + incoming + "在线");

        //写入并发送信息到远端（客户端）
        String strDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss SSS"));
        ctx.writeAndFlush(Unpooled.copiedBuffer("这是服务器在 Active 中反馈的信息 " + strDateTime + "\r\n", CharsetUtil.UTF_8));
    }

    //通道失去活动状态触发的动作，该方法只会在通道失效时调用一次
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        System.out.println("客户端：" + incoming + "掉线");

        //写入并发送信息到远端（客户端）
        String strDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss SSS"));
        ctx.writeAndFlush(Unpooled.copiedBuffer("这是服务器在 Inactive 中反馈的信息 " + strDateTime + "\r\n", CharsetUtil.UTF_8));
    }
}
